import HttpRequest from "@/utils/HttpRequest";
import store from "@/store";
import CacheUtils from "@/utils/CacheUtils";
import Modal from "@/utils/Modal";
import {getCurrentPage} from "@/utils/CommonUtils";

const needLoginPath = [];


class LoginService {

  /**
   * @description 判断是否登录
   */
  hasLogin() {
    return !!CacheUtils.getCache('token') || !!CacheUtils.getCache('sessionId');
  }

  /**
   * @description 判断 需要登录的页面
   */
  async needLogin(url) {
    // 截取？前面的路径
    const src = url.split('?')[0];
    return !await this.hasLogin() && needLoginPath.includes(src);
  }

  /**
   * @description 判断有无登录 带提示的  并且去登录
   * @param {string} url 路径
   * @param {boolean} hasTabBar 是否是tabbar页面
   * @param {boolean} hasClose 是否需要关闭当前页面
   */
  async checkLogin(url, hasTabBar = false, hasClose = false) {
    if (await this.needLogin(url)) {
      Modal.confirm('当前未登录,是否前去登录').then(async (res) => {
        if (res) {
          await uni.navigateTo({url: '/pages/login/index'});
        }
      })
      return
    }
    hasTabBar ? await uni.switchTab({url,}) : (hasClose ? await uni.redirectTo({url}) : await uni.navigateTo({url,}));
  }

  /**
   * @description 微信默认登录 code
   * @param {Object} form
   * @return {Promise<void>}
   */
  async WXCodeLogin(form) {
    try {
      const {code} = await uni.login();
      const data = form ? form : {code};
      const res = await HttpRequest.post({url: `/index/smapp/base/login`, data: {}, params: data});
      store.commit('user/changeUser', res);
      CacheUtils.setCache('token', res.token);
      const page = await getCurrentPage(1);
      await uni.reLaunch({
        url: page.$page.fullPath
      });
    } catch (err) {
      Toast.info(err);
    }
  }

  /**
   * @description 退出登录
   * @return {Promise<void>}
   */
  logout() {
    CacheUtils.clearCache();
    store.commit('user/changeUser', {});
  }


}

export default new LoginService();
